/** 
 * projectName:  
 * fileName:  
 * packageName:  
 * date: 
 * copyright(c) 2017-2020 xxx公司
 */
package cn.message.web;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import cn.itcast.pojo.admin;
import cn.itcast.util.CookieUtil;
import cn.itcast.util.OutputStringController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;


import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

/**   
 * @title: homeController.java 
 * @package com.job.controller 
 * @description: TODO
 * @author: 欧阳辉
 * @date: 2019年1月24日 下午8:57:15 
 * @version: V1.0   
*/
@RestController
@RequestMapping(value="/wxshop/message",produces="text/html;charset=UTF-8")
@Slf4j
public class adminController {



	@Resource
	private cn.message.service.adminService adminService;
	@Resource
    OutputStringController osc;
	@Resource
    CookieUtil cookieUtil;

	@RequestMapping("/tologin")
    @ResponseBody
	public String tologin(){
	    log.debug("没有登录，跳转到登录页面");
	    return osc.failure("跳转到登录页面");
    }


	@RequestMapping("/noAuth")
    @ResponseBody
	public String noAuth(){
		log.debug("管理员没有该权限");
		return osc.noAuth("您没有没有权限访问");
	}

	/**   
	 * @title:   admin
	 * @description: 验证数据是否正确
	 * @param:  
	 * @throws:   
	 */
	@PostMapping("/check")
    @ResponseBody
	public String check(HttpServletResponse response,String adminNickname ) {
		log.debug("管理员名称："+adminNickname);
		boolean ischeck = adminService.usernameChecked(adminNickname);
		//初始化返回信息
		String msg="";
		String results="";
		if(ischeck) {
			msg = "yes";
			results=osc.success(msg);
			System.out.println("管理员名称验证成功");
		}else {
			msg = "no";
			results=osc.failure(msg);
			System.out.println("管理员名称验证失败");
		}
		return results;
	}
	/**   
	 * @title:   admin
	 * @description: 管理员登录
	 * @param:  
	 * @throws:   
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/login", produces = "application/json;charset=UTF-8")
    @ResponseBody
	public String login(HttpServletRequest request,HttpServletResponse response,@RequestBody Map<String,String> map) {
//		HttpSession session = request.getSession();
//		String adminNickname = map.get("adminNickname");
//		String adminPassword = map.get("adminPassword");
//		//验证身份
//		Map<String,Object> resultMap = adminService.login(response,adminNickname,adminPassword,session);
//		String results = "";
//		if((boolean) resultMap.get("islogin")) {
//			admin admin = adminService.getUserByLoginName(adminNickname);
//			//设置admin登录状态
//			boolean isstate = adminService.changeLoginState(admin.getAdminId(),1);
//			results = osc.resultSuccess("yes", resultMap.get("admin"));
//		}else{
//			results = osc.failure("no");
//		}
//		return results;

        String results = "";
        Subject subject = SecurityUtils.getSubject();
        HttpSession session = request.getSession();
        String adminNickname = map.get("adminNickname");
        String adminPassword = map.get("adminPassword");
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(adminNickname, adminPassword);
        try {
            subject.login(usernamePasswordToken);

            Map<String, Object> map1 = adminService.login(response, adminNickname, adminPassword, session);

            results = osc.resultSuccess("登录成功",map1);
        } catch (UnknownAccountException e) {
            //e.printStackTrace();
            //登录失败:用户名不存在
            return osc.failure("用户名不存在");
        }catch (IncorrectCredentialsException e) {
            //e.printStackTrace();
            //登录失败:密码错误
            return osc.failure("密码错误");
        }catch (LockedAccountException e) {
            return osc.freezed("登录失败，该用户已被冻结");
        }
        return results;
	}
	
	/**   
	 * @title:   admin
	 * @description: 管理员登录
	 * @param:  
	 * @throws:   
	 */
	@RequestMapping(value="/edit", produces = "application/json;charset=UTF-8")
    @ResponseBody
	public String edit(HttpServletRequest request,HttpServletResponse response, @RequestBody Map<String,String> map) {
		HttpSession session = request.getSession();
		Cookie[] cookies = request.getCookies();
		//cookie中的token
		String token = "";
		if(StringUtils.isNotBlank(ObjectUtils.toString(cookies))) {
			for (Cookie cookie : cookies) {
			    switch(cookie.getName()){
			        case "token":
			            token = cookie.getValue();
			            break;
			        default:
			            break;
			    }
			}
		}
		Integer adminId = Integer.parseInt(map.get("adminId"));
		//设置admin登录状态
		boolean isstate = adminService.changeLoginState(adminId,0);
		boolean isedit = adminService.edit(response,session,token);
		String results = "";
		if(isstate && isedit) {
			results = osc.success("yes");
		}else{
			results = osc.failure("no");
		}
		return results;
	}
	/**   
	 * @title:   admin
	 * @description: 管理员信息获取
	 * @param:  
	 * @throws:   
	 */
	@RequestMapping(value="/findMsg", produces = "application/json;charset=UTF-8")
    @ResponseBody
	public String findMsg(HttpServletRequest request,@RequestBody Map<String,String> map) {
		HttpSession session = request.getSession();
		Integer adminId = Integer.parseInt(map.get("adminId"));
		Cookie[] cookies = request.getCookies();
		//cookie中的token
		String token = "";
		for (Cookie cookie : cookies) {
		    switch(cookie.getName()){
		        case "token":
		            token = cookie.getValue();
		            break;
		        default:
		            break;
		    }
		}
		//设置admin登录状态
		admin admin = adminService.getUserMsg(adminId,token);
		String results = "";
		if(admin != null) {
			results = osc.resultSuccess("yes", admin);
		}else{
			results = osc.resultFailure("no", admin);
		}
		return results;
	}
	/**   
	 * @title:   user
	 * @description: 管理员修改数据   
	 * @param:  
	 * @throws:   
	 */

	@JsonIgnoreProperties(ignoreUnknown = true)//忽略未知属性
	@RequestMapping(value="/updateAdmin", produces = "application/json;charset=UTF-8",method = RequestMethod.POST)
    @ResponseBody
	public String updateUser(HttpServletRequest request,@RequestBody Map<String,String> map) {
		HttpSession session = request.getSession();
		Integer adminId = Integer.parseInt(map.get("adminId"));
		String adminNickname = map.get("adminNickname");
		String adminPassword = map.get("adminPassword");
		String adminName = map.get("adminName");
		String adminPhone = map.get("adminPhone");
		String adminAddress = map.get("adminAddress");
		admin admin = new admin();
		admin.setAdminId(adminId);
		admin.setAdminAddress(adminAddress);
		admin.setAdminName(adminName);
		admin.setAdminNickname(adminNickname);
		admin.setAdminPassword(adminPassword);
		admin.setAdminPhone(adminPhone);
		boolean isupdate = adminService.updateAdmin(admin);
		String results = "";
		if(!isupdate) {
			results=osc.failure("no");
			System.out.println("修改管理员失败");
		}else {
			results = osc.success("yes");
			System.out.println("修改管理员成功");
		}
		return results;
	}
	/**   
	 * @title:   user
	 * @description: 管理员上传头像   
	 * @param:  
	 * @throws:   
	 */
	/*
     *采用spring提供的上传文件的方法
     */
    @RequestMapping("/updatePicture")
    @ResponseBody
    public String  springUpload(HttpServletRequest request) throws IllegalStateException, IOException
    {
		//上传是否成功
		boolean isupload = false;
		//返回结果
		String results = "";
		//获取管理员id
		Integer adminId = Integer.parseInt(request.getParameter("adminId"));
         long  startTime=System.currentTimeMillis();
         //将当前上下文初始化给  CommonsMutipartResolver （多部分解析器）
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request))
        {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
           //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();
             
            while(iter.hasNext())
            {
                //一次遍历所有文件
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                if(file!=null)
                {
                	//服务器图片路径
                    String path="/usr/tomcat/images/adminheader/"+adminId+"/"+file.getOriginalFilename();
                    File files=new File("/usr/tomcat/images/adminheader/"+adminId);
            		if(!files.exists()){//如果文件夹不存在
            			files.mkdir();//创建文件夹
            		}
                    //头像路径
                    String imgpath = "http://www.dhnep.cn:8181/adminheader/"+adminId+"/"+file.getOriginalFilename();
                    isupload = adminService.imageUpload(imgpath,adminId);
                    if(isupload) {
                    	//上传
                    	file.transferTo(new File(path));
                    	results = osc.resultSuccess("yes", imgpath);
                    	System.out.println("管理员头像上传成功");
                    }else {
                    	results = osc.failure("no");
                    	System.out.println("管理员头像上传失败");
                    }
                }
                 
            }
           
        }
        long  endTime=System.currentTimeMillis();
        System.out.println("方法三的运行时间："+String.valueOf(endTime-startTime)+"ms");
		return results;
    }



	
}






